import { TagItem, TagState } from '@/types'

import type { PayloadAction } from '@reduxjs/toolkit'
import { createSlice } from '@reduxjs/toolkit'

const initialState: TagState = {
  activeTagId: location.pathname, // 设置活动标签的初始值为当前页面路径
  tags: [
    {
      icon: 'HomeOutlined',
      key: '',
      label: {
        zh: '首页',
        en: 'Home'
      },
      closable: false
    }
  ] // 初始化标签数组为空
}

const tabStoreData = createSlice({
  name: 'tagsView',
  initialState,
  reducers: {
    //触发标签
    activeTabs(state, action: PayloadAction<string>) {
      state.activeTagId = action.payload // 将传入的标签 ID 设置为活动标签
    },
    //  添加标签
    addTabs(state, action: PayloadAction<TagItem>) {
      if (!state.tags.find((ele) => ele.key === action.payload.key)) {
        state.tags.push(action.payload)
      }
      state.activeTagId = action.payload.key
    },
    // 删除标签
    removeTabs(state, action: PayloadAction<string>) {
      // 获取要移除的标签路径
      const targetKey = action.payload
      // dashboard 不能被关闭
      const activeTagId = state.activeTagId // 保存当前活动标签的路径
      let lastIndex = 0 // 初始化最后一个索引为 0
      // 遍历标签数组

      state.tags.forEach((tag, i) => {
        if (tag.key === targetKey) {
          state.tags.splice(i, 1) // 移除匹配的标签
          lastIndex = i - 1 // 更新最后一个索引
        }
      })
      const tagList = state.tags.filter((tag) => tag.key !== targetKey) // 过滤掉被移除的标签
      // 更新活动标签的路径

      if (tagList.length && activeTagId === targetKey) {
        if (lastIndex >= 0) {
          state.activeTagId = tagList[lastIndex].key // 设置为前一个标签的路径
        } else {
          state.activeTagId = tagList[0].key // 设置为第一个标签的路径
        }
      }
    }
  }
})

export const { addTabs, removeTabs, activeTabs } = tabStoreData.actions
const useFrontStore = tabStoreData.reducer

export default useFrontStore
